﻿using Qy.Core;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class UserDeptService : QyRepository<UserDept>
{
    public UserDeptService(ApplicationContext applicationContext) : base(applicationContext)
    {
    }

    /// <summary>
    /// 全部列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<UserDept>> GetAllAsync()
    {
        return await GetAllListAsync("Id desc");
    }

    public async Task<UserDept> GetInfo(int id)
    {
        List<UserDept> userDepts = await GetAllAsync();
        return userDepts?.Find(a => a.Id == id);
    }


    #region 获取所有下级

    /// <summary>
    /// 获取当前部门及子部门ID值字符串
    /// </summary>
    /// <param name="Pid"></param>
    /// <returns></returns>
    public async Task<List<int>> GetDeptAndSonIdsAsync(int Pid)
    {
        List<UserDept> userDepts = await GetAllAsync();
        var query = userDepts.Where(p => p.Id == Pid).ToList();
        var list2 = query.Concat(GetSonList(userDepts, Pid));
        List<int> ids = list2.Select(o => o.Id).ToList();
        //ids.Add(Pid);//包含自己
        return ids;
    }

    public static IEnumerable<UserDept> GetSonList(IList<UserDept> list, int Pid)
    {
        var query = list?.Where(p => p.Pid == Pid).ToList();
        return query.ToList().Concat(query?.ToList().SelectMany(t => GetSonList(list, t.Id)));
    }
    #endregion

    /// <summary>
    /// 获取所有上级
    /// </summary>
    /// <param name="list"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public static IEnumerable<UserDept> GetFatherList(IList<UserDept> list, int Id)
    {
        var query = list?.Where(p => p.Id == Id).ToList();
        return query.ToList().Concat(query?.ToList().SelectMany(t => GetFatherList(list, t.Pid)));
    }


    public async Task<object> Insert(EditUserDept adminUserDept)
    {
        UserDept userDept = new()
        {
            Pid = adminUserDept.Pid,
            Name = adminUserDept.Name,
            OrderNum = adminUserDept.OrderNum,
            Remark = adminUserDept.Remark
        };
        return await InsertAsync(userDept);
    }

    public async Task<int> UpdateContentCatRoleAsync(ContentCatRole contentCatRole)
    {
        UserDept user = await GetInfo(contentCatRole.Id);
        if (contentCatRole.ContentCateRole != null)
            user.ContentCateRole = contentCatRole.ContentCateRole;
        if (0 < await UpdateAsync(user)) return 1;
        return 0;
    }
    public async Task<int> UpdateDocCatRoleAsync(DocCatRoles docCatRole)
    {
        UserDept user = await GetInfo(docCatRole.Id);
        if (docCatRole.DocCatRole != null)
            user.DocCatRole = docCatRole.DocCatRole;
        if (0 < await UpdateAsync(user)) return 1;
        return 0;
    }

    public async Task<bool> DeleteDelCache(int id)
    {
        bool checkUser = await Context.Queryable<User>().AnyAsync(data => data.DeptId == id);
        bool checkSonDept = await GetDeptAndSonIdsAsync(id) != null;
        if (!checkUser && !checkSonDept)
            return await DeleteAndDelCacheAsync(id) > 0;
        return false;
    }

    public async Task<IEnumerable<CategoryViewModel>> GetUserDeptListAsync()
    {
        List<UserDept> cates = await GetAllAsync();
        return cates.AsCateListItems();//导出带 所有栏目封装数据
    }

    /// <summary>
    /// 输出JSON 树形栏目列表 内容管理的菜单列表使用
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<CategoryViewModel>> AsUserDeptTree()
    {
        var cates = await GetAllAsync();
        List<CategoryViewModel> treeModels = new();
        var cateModels = cates.AsViewCategoryModels();
        CategoryExtensions.IndentedContentCates(cateModels, treeModels);
        return treeModels;
    }

    /// <summary>
    /// 列表
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<ViewUserDept>> GetUserDepts()
    {
        return await GetUserDepts(0, await GetAllAsync());
    }

    /// <summary>
    /// 递归栏目树
    /// </summary>
    /// <returns></returns>
    private async Task<List<ViewUserDept>> GetUserDepts(int pid, List<UserDept> depts = null)
    {
        var parent = depts.Where(P => P.Pid == pid);
        List<ViewUserDept> lists = new();
        foreach (var item in parent)
        {
            ViewUserDept Childer = new()
            {
                Id = item.Id,
                Name = item.Name,
                OrderNum = item.OrderNum,
                Remark = item.Remark,
                GreatTime = item.GreatTime,
            };
            Childer.Children = await GetSon(Childer, depts);
            if (Childer.Children != null)
            {
                Childer.HaveChild = true;
                Childer.Open = true;
            }
            lists.Add(Childer);
        }
        async Task<List<ViewUserDept>> GetSon(ViewUserDept cates, List<UserDept> sonCates = null)
        {
            if (!sonCates.Exists(x => x.Pid == cates.Id))
            {
                return null;
            }
            else
            {
                return await GetUserDepts(cates.Id, sonCates);
            }
        }
        return lists.OrderBy(o => o.OrderNum).ThenBy(o => o.Id).ToList();
    }
}
